package dongfeng.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JSONObject;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.monitor.cache.Util.MD5;

public class DFEditEnterprise {
	public static Log log = LogFactory.getLog(DFEditEnterprise.class);

	// 新增人员
	/**
	 * 
	 * @param userid //当前用户
	 * @param qymc	//修改后的企业名称
	 * @param qyjc	//修改后的企业简称
	 * @param qyfr	//修改后企业法人名称
	 * @param yddh	//修改后的电话
	 * @param bmhx	//部门id固定(编辑无法修改部门id)
	 * @param qyfrhx	//修改前的法人id
	 * @return
	 */
	public static JSONObject addHrmresourceAndDept(String userid, String qymc, String qyjc, String qyfr, String yddh,
			String bmhx,String qyfrhx) {
		log.info("=======================Enterprise Eidt start.");
		log.info("userid:" + userid );
		JSONObject resultObj = new JSONObject();// 返回参数
		if (qymc == null || qyjc == null || qyfr == null || yddh == null) {
			// 全部正常
			resultObj.put("code", -1);
			resultObj.put("msg", "传输参数错误");
			return resultObj;
		}
		if ("".equals(qymc) || "".equals(qyjc) || "".equals(qyfr) || "".equals(yddh)) {
			// 全部正常
			resultObj.put("code", -1);
			resultObj.put("msg", "传输参数错误");
			return resultObj;
		}

		// 获取当前日期、时间
		String currTime = new SimpleDateFormat("HH:mm:ss").format(new Date());
		String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		RecordSet recordSet = new RecordSet();
		// 新建部门、人员时部分默认信息
		String subId = recordSet.getPropValue("DFZQXT", "subid"); // 默认分部ID
		String jobtitleId = recordSet.getPropValue("DFZQXT", "jobtitleId"); // 默认岗位ID
		int EnterpriseModeId = 45; // 企业信息模块ID
		int EPContactsModeId = 46; // 企业联系人模块ID
		String locationId = recordSet.getPropValue("DFZQXT", "locationId"); // 办公地点ID

		int systemlanguage = 7; // 系统预言int
		String maritalstatus = "0"; // 婚姻状况char，默认0
		int joblevel = 0; // int 工作级别
		String jobactivitydesc = "";// 职责描述
		int seclevel = 10;// 安全级别
		String workcode = "";// 编号
		Double dsporder = 0.0; // 显示顺序
		int accounttype = 0; // 账号类型
		int belongto = -1; // 所属主账号

		String bmid = bmhx;//编辑保存部门id不变
		
		String qyfrid2=qyfrhx;
		RecordSetTrans recordSetTrans = new RecordSetTrans();
	//	if(deptIsChange(bmid, qymc, qyjc)) {//部门名称有修改，则更新部门表的名称
			
			if (deptExists(qymc,bmid)) { //判断修改的部门名称是否存在
				resultObj.put("code", 1);
				resultObj.put("msg", qymc + "部门已存在");
				return resultObj;
			}
			try {
				updateDept(recordSetTrans, qyjc, qymc, GetAllFirstLetter.getAllFirstLetter(qymc),bmhx );
			} catch (Exception e) {
				e.printStackTrace();
				log.info("更新部门表部门名称失败");
				resultObj.put("code", 2);
				resultObj.put("msg", "更新部门表部门名称失败");
				return resultObj;
			}
	//	}
		try {
			if (qyfrIsChange(qyfr, yddh, qyfrhx)) {//企业法人有改变
				qyfrid2=CreateEmpt(recordSetTrans, qyfr, yddh, bmid, subId, userid, jobtitleId, locationId, currDate);	
				// 部门、人员创建完成后，更新下一个人员的生成ID
				UpdateHrmresourceID(recordSetTrans, Integer.parseInt(qyfrid2));
			}
			//更新联系人中相关的企业法人和企业信息
			updateContacts(recordSetTrans, bmid, qyjc, qyfr, yddh, qyfrid2);
			//更新旧法人的信息
			updateOldqyfr(recordSetTrans, qyfrhx, bmid);
			
			recordSetTrans.commit();
		}catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			recordSetTrans.rollback();
			resultObj.put("code", 3);
			resultObj.put("msg", e.getMessage());
			return resultObj;
		}
		
		// 全部正常
		resultObj.put("code", 0);
		resultObj.put("msg", "ok");
		resultObj.put("bmhx", bmid);
		resultObj.put("qyfrhx", qyfrid2);

		return resultObj;
	}

	/**
	 *	更新（企业）部门
	 * 
	 * @param qyjc          （企业）部门简称
	 * @param qymc          （企业）部门名称
	 * @param bmid          部门id
	 * @param pinyin_search 快速搜索代码
	 * @throws Exception 
	 */
	private static void updateDept(RecordSetTrans rSetTrans, String qyjc, String qymc, String pinyin_search,
			String bmid) throws Exception {
			log.info("更新部门开始");
			DepartmentComInfo deComInfo = new DepartmentComInfo();
			String updateDP="update HrmDepartment set departmentmark='"+qyjc+"', departmentname='"+qymc+"',ecology_pinyin_search='"
			+pinyin_search+"' where id="+ bmid;
			rSetTrans.executeUpdate(updateDP);
			// rSetTrans.commit();
			log.info(updateDP);
			// 移除部门缓存
			deComInfo.removeCache();
			deComInfo.removeCompanyCache();
			log.info("更新部门结束");

	}

	/**
	 * 	 判断修改的企业名称是否被其它企业已经占用
	 * 
	 * @param qymc
	 * @return
	 */
	private static boolean deptExists(String qymc,String bmhx) {
		boolean flag = false;
		RecordSet rSet1 = new RecordSet();
		// 根据名称查询没有封存的部门id
		String getDpid = "select * from HrmDepartment where departmentname='" + qymc + "' and isnull(canceled,0)<>1 and id<>"+bmhx;
		log.info("查询所创建的部门是否存在:" + getDpid);
		rSet1.execute(getDpid);
		if (rSet1.next()) {
			flag = true;
		}
		return flag;
	}
	/**
	 * 	查询所修改的部门名称是否有变动
	 * @param bmid
	 * @param qymc
	 * @param qyjc
	 * @return
	 */
	private static boolean deptIsChange(String bmid,String qymc ,String qyjc) {
		boolean flag = true;
		RecordSet rs = new RecordSet();
		// 根据名称查询没有封存的部门id
		String getDpid = "select * from HrmDepartment where id="+bmid+" and departmentmark='"+qyjc+"' and  departmentname='" + qymc + "' and isnull(canceled,0)<>1";
		log.info("查询id的部门是有变:" + getDpid);
		rs.execute(getDpid);
		if (rs.next()) {//查询到，则没有变化
			flag = false;
		}
		return flag;
	}

	/**
	 * 	判断法人是否已存在OA中
	 * 
	 * @param qyfr
	 * @param yddh
	 * @return
	 */
	private static String qyfrExists(String qyfr, String yddh) {
		String id = null;
		RecordSet rSet1 = new RecordSet();

		String getDpid = "select * from hrmresource where lastname='" + qyfr + "' and mobile='" + yddh + "'";
		log.info("查询所创建的人:" + getDpid);
		rSet1.execute(getDpid);
		if (rSet1.next()) {
			id = rSet1.getString("id");
		}
		return id;
	}
	
	/**
	 * 	判断企业法人是否已经改变
	 * @param qyfr
	 * @param yddh
	 * @param qyfrhx
	 * @return
	 */
	private static boolean qyfrIsChange(String qyfr, String yddh,String qyfrhx) {
		boolean flag=true;
		RecordSet rSet1 = new RecordSet();

		String getDpid = "select * from hrmresource where id="+qyfrhx+" and lastname='" + qyfr + "' and mobile='" + yddh + "'";
		log.info("查询企业法人是否已经改变:" + getDpid);
		rSet1.execute(getDpid);
		if (rSet1.next()) {
			flag=false;
		}
		return flag;
	}

	/**
	 * 产生新的人员信息编号
	 * 
	 * @return result
	 */
	private static int getHrmresourceID() {
		int result = -1;
		try {
			String sql = "select currentid from sequenceindex where indexdesc='resourceid'";
			RecordSet rs = new RecordSet();
			rs.execute(sql);
			while (rs.next())
				result = Util.getIntValue(rs.getString("currentid"), 0);
		} catch (Exception e) {
			log.error("获取新的人员信息编号错误");
		}
		log.info("本次获取的sequenceindex-ID为：" + result);
		return result;
	}

	/**
	 * 更新下个人员ID
	 * 
	 * @param id
	 */
	private static void UpdateHrmresourceID(RecordSetTrans rs, int id) throws Exception {
		String sql = "update sequenceindex set currentid='" + (id + 1) + "' " + "where indexdesc='resourceid'";
		log.info("SQL-UpdateHrmresourceID:" + sql);
		try {
			rs.execute(sql);
			// rs.commit();
		} catch (Exception e) {
			// rs.rollback();
			log.error("更新人员编号失败");
			throw new Exception("更新人员编号失败");
		}
	}

	/**
	 * 创建企业法人信息
	 * 
	 * @param recordSetTrans
	 * @param qyfr           法人姓名 （与密码一致）
	 * @param bmid           所属部门ID
	 * @param userid
	 * @param currDate
	 */
	public static String CreateEmpt(RecordSetTrans recordSetTrans, String qyfr, String yddh, String bmid, String subId,
			String userid, String jobtitleId, String locationId, String currDate) throws Exception {
		
		String id=qyfrExists(qyfr, yddh);
		if (id==null) {

			ResourceComInfo resourceComInfo = new ResourceComInfo();
			int hrmId = getHrmresourceID();
			try {
				log.info("创建人员开始");
				// 人力资源缓存对象
				String createHRM = "insert into HrmResource(" + " id,lastname,loginid,mobile,"
						+ "password,departmentid,jobtitle," + "status,subcompanyid1,createrid,createdate,locationid,"
						+ "systemlanguage,maritalstatus,joblevel,jobactivitydesc,seclevel,workcode,"
						+ "dsporder,accounttype,belongto,mobileshowtype) " + " values(" + hrmId + " , '" + qyfr + "' , '"
						+ qyfr + "' , '" + yddh + "'," + "'" + MD5.MD5Encode("1").toUpperCase() + "' , " + bmid + " , "
						+ jobtitleId + " , " + 1 + " , " + subId + " , " + userid + " , '" + currDate + "' ," + locationId
						+ "," + "7,'0',0,' ',10,' '," + hrmId + ",0,-1,2)";
				recordSetTrans.execute(createHRM);
				// recordSetTrans.commit();
				log.info("createHRM:" + createHRM);
				// 移除人力资源缓存
				resourceComInfo.removeCache();
				resourceComInfo.removeResourceCache();
				String queryHRMSQL = "select id from hrmresource where loginid = '" + qyfr + "' and mobile='"+yddh+"' and departmentid="+bmid;
				recordSetTrans.executeQuery(queryHRMSQL);
				if (recordSetTrans.next()) {
					id= recordSetTrans.getString("id");
				}else {
					log.info("获取所创建人员的ID失败");
					throw new Exception("获取所创建人员的ID失败");
				}
				
			} catch (Exception e) {
				log.info(e);
				throw new Exception("插入人员失败");
			}
		}
		//将员工在职状态变为1正式
		String sql="update hrmresource set status=1 where id="+id;
		recordSetTrans.executeUpdate(sql);
		return id;
	}
	/**
	 * 	更新旧的企业法人信息
	 * @param recordSetTrans
	 * @param oldqyfrhx
	 * @param bmid
	 * @throws Exception 
	 */
	private static void  updateOldqyfr(RecordSetTrans recordSetTrans,String oldqyfrhx,String bmid) throws Exception {
		
		String sql="select  *  from uf_EPContacts where qyfr='"+oldqyfrhx+"' or lxrhx='"+oldqyfrhx+"'";
		recordSetTrans.executeQuery(sql);
		RecordSet rs=new RecordSet();
		String departmentidsql="select * from hrmresource where id ="+oldqyfrhx;
		rs.execute(departmentidsql);
		//如果查询到
		if (recordSetTrans.next()&&rs.next()) {
			if (bmid.equals(rs.getString("departmentid"))) {//如果更改的企业部门是旧联系人所在部门则更新旧所在部门
				String updatehrmresource="update hrmresource set departmentid="+recordSetTrans.getString("qymc")+" where id="+oldqyfrhx;
				log.info("如果旧法人没有其它关联信息，更新旧法人离职状态:"+updatehrmresource);
				recordSetTrans.execute(updatehrmresource);
			}
			
		}else {
			String updatehrmresource="update hrmresource set status=5 where id="+oldqyfrhx;
			log.info("如果旧法人没有其它关联信息，更新旧法人离职状态:"+updatehrmresource);
			recordSetTrans.execute(updatehrmresource);
		}
		ResourceComInfo resourceComInfo=new ResourceComInfo();
		// 移除人力资源缓存
		resourceComInfo.removeCache();
		resourceComInfo.removeResourceCache();
	}
	/**
	 * 	更新企业联系人表中的企业简称和企业法人根据企业部门id(qymc)
	 * @param recordSetTrans
	 * @param bmid
	 * @param qyjc
	 * @param qyfr
	 * @param lxdh
	 * @param qyfrhx
	 * @throws Exception 
	 */
	private static void updateContacts (RecordSetTrans recordSetTrans,String bmid,String qyjc,String qyfr,String lxdh,String qyfrhx) throws Exception {
		String updateqyfr="update uf_EPContacts set qyjc='"+qyjc+"',lxr='"+qyfr+"',lxdh='"+lxdh+"',qyfr="+qyfrhx+",lxrhx="+qyfrhx+" where qymc="+bmid +" and qyfr=lxrhx";
		log.info("变更企业信息联动更新企业联系人中法人的联系信息："+updateqyfr);
		recordSetTrans.executeUpdate(updateqyfr);
		String sql="update uf_EPContacts set qyjc='"+qyjc+"',qyfr="+qyfrhx+" where qymc="+bmid;
		log.info("变更企业信息联动更新企业联系人中除法人外的信息："+sql);
		recordSetTrans.executeUpdate(sql);
	}
}
